#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
struct ListNode {
   int val;
   struct ListNode *next;
};
typedef struct ListNode ListNode;
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    ListNode* pre = NULL, * mid = l1, * Next = NULL;
    while (mid) {
        if (mid != NULL) {
            Next = mid->next;
        }
        mid->next = pre;
        pre = mid;
        mid = Next;
    }
    ListNode* head1 = pre;
    mid = l2; pre = NULL;
    while (mid) {
        if (mid != NULL) {
            Next = mid->next;
        }
        mid->next = pre;
        pre = mid;
        mid = Next;
    }
    ListNode* head2 = pre;
    ListNode* newhead = NULL, * newtail = NULL;
    int x = 0; int num = 0;
    while (head1 && head2) {
        ListNode* ptr = (ListNode*)malloc(sizeof(ListNode));
        x = head1->val + head2->val + num;
        ptr->val = x % 10;
        ptr->next = NULL;
        if (x >= 10) {
            num = 1;
        }
        else {
            num = 0;
        }
        if (newhead == NULL) {
            newhead = newtail = ptr;
        }
        else {
            newhead = ptr;
            newhead->next = newtail;
            newtail = newhead;
        }
        head1 = head1->next;
        head2 = head2->next;
    }
    if (head1 == NULL && head2 == NULL) {
        if (num == 1) {
            ListNode* ptr = (ListNode*)malloc(sizeof(ListNode));
            ptr->val = num;
            newhead = ptr;
            newhead->next = newtail;
            newtail = newhead;
        }
    }
    else {
        pre = newhead;
        mid = head1 == NULL ? head2 : head1;
        while (mid) {
            if (mid != NULL) {
                Next = mid->next;
            }
            x = mid->val + num;
            mid->val = x % 10;
            if (x >= 10) {
                num = 1;
            }
            else {
                num = 0;
            }
            mid->next = pre;
            pre = mid;
            mid = Next;
        }
        newhead = pre;
        if (num == 1) {
            ListNode* ptr = (ListNode*)malloc(sizeof(ListNode));
            ptr->val = num;
            newhead = ptr;
            newhead->next = pre;
        }
    }
    return newhead;
}
int main() {
    ListNode p1, p2, p3, p4, p5, p6, p7;
    p1.val = 1, p1.next =NULL;
    /*p2.val = 2, p2.next = &p3;
    p3.val = 4, p3.next = &p4;
    p4.val = 3, p4.next = NULL;
    p5.val = 5, p5.next = &p6;*/
    p6.val = 9, p6.next = &p7;
    p7.val = 9, p7.next =NULL;
    addTwoNumbers(&p1, &p6);

}